package down.xiaoheihe.work.Controller;

import down.xiaoheihe.work.Mapper.Mysql;
import down.xiaoheihe.work.Service.OssService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@RestController
@CrossOrigin
@MapperScan("down.xiaoheihe.work.Mapper")
public class OSSController {
    @Autowired
    Mysql mysql;
    @Resource(name = "TencentOssService")
    private OssService ossService;
    @PostMapping("/upload")
    public @ResponseBody String upLoadImage(@RequestParam Integer id, @RequestParam String username, @RequestParam MultipartFile[] file, HttpServletResponse response) {
        for (MultipartFile multipartFile : file) {
            try {
                String url = ossService.uploadFileAvatar(multipartFile, username);
                String newUrl = "http://" + url;
                System.out.println(username + "upload:" + newUrl);
                mysql.insert(id, newUrl);
            } catch (java.lang.Exception e) {
                e.printStackTrace();
                response.setStatus(500);
                return "Error";
            }
        }
        return "OK";
    }
    @PostMapping("/touxiang")
    public @ResponseBody String upLoadTouXiang(@RequestParam Integer id, @RequestParam String username, @RequestParam MultipartFile file, HttpServletResponse response){
        try {
            String url = ossService.uploadFileAvatar(file, username);
            String newUrl = "http://" + url;
            mysql.update(id, newUrl);
            return "OK";
        } catch (java.lang.Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            return "Error";
        }
    }
}
